package ro.mfl.sockets.client;

import java.io.*;
import java.net.Socket;
import java.util.Calendar;


public class Client {
    private Socket socket;
    private BufferedReader reader;
    private PrintWriter writer;

    public void openConnection() throws IOException {
        socket = new Socket("127.0.0.1", 9999);
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new PrintWriter(socket.getOutputStream(), true);
        Calendar cal = Calendar.getInstance();
        writer.println("CONNECT-" + cal.getTimeInMillis());
    }

    public void closeConnection() throws  IOException {
        reader.close();
        writer.close();
        socket.close();
    }

    public void communicate() throws InterruptedException {
        ReaderThread readerThread = new ReaderThread(reader);
        readerThread.start();

        WriterThread writerThread = new WriterThread(writer);
        writerThread.start();

        readerThread.join();
        writerThread.join();
    }

    public static void main(String[] args) {
        Client client = new Client();
        try {
            client.openConnection();
            client.communicate();
            client.closeConnection();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

}


class ReaderThread extends Thread {

    private final BufferedReader reader;

    ReaderThread(BufferedReader reader) {
        this.reader = reader;
    }

    public void run() {
        System.out.println("start client read thread");
        try {
            while(true) {
                String line = reader.readLine();
                if(line.equalsIgnoreCase("quit client"))
                    return;
                System.out.println(line);
            }
        }
        catch(Exception e) {
            System.out.println("ERROR");
            e.printStackTrace();
        }
    }
}

class WriterThread extends Thread {
    private final PrintWriter writer;

    WriterThread(PrintWriter writer)
    {
        this.writer = writer;
    }

    public void run() {
        try {
            System.out.println("start client write thread");
            while(true) {
                BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
                String line = consoleReader.readLine();
                writer.println(line);

            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}